package com.example.managemyself.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.managemyself.config.AppConfig;

import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * API连接测试工具类
 * 用于测试和诊断API连接问题
 */
public class ApiConnectionTester {
    private static final String TAG = "ApiConnectionTester";
    
    // 测试结果回调接口
    public interface TestCallback {
        void onSuccess(String message);
        void onError(String error);
        void onProgress(String progress);
    }
    
    // HTTP客户端配置
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build();
    
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    /**
     * 测试API连接
     */
    public static void testApiConnection(Context context, TestCallback callback) {
        if (callback != null) {
            mainHandler.post(() -> callback.onProgress("开始测试API连接..."));
        }
        
        executor.execute(() -> {
            try {
                // 1. 检查网络连接
                if (!NetworkUtils.isNetworkAvailable(context)) {
                    notifyError(callback, "网络不可用，请检查网络连接");
                    return;
                }
                
                notifyProgress(callback, "网络连接正常，正在测试API服务器...");
                
                // 2. 获取API配置
                AppConfig config = AppConfig.getInstance();
                String baseUrl = config.getApiBaseUrl();
                if (baseUrl == null || baseUrl.contains("your_server")) {
                    notifyError(callback, "API服务器地址未配置，请在设置中配置API地址");
                    return;
                }
                
                // 3. 构建健康检查URL
                String healthCheckUrl = baseUrl.endsWith("/") ? 
                    baseUrl + "health/check" : baseUrl + "/health/check";
                
                notifyProgress(callback, "正在连接: " + healthCheckUrl);
                
                // 4. 发送HTTP请求
                Request request = new Request.Builder()
                        .url(healthCheckUrl)
                        .addHeader("Accept", "application/json")
                        .addHeader("User-Agent", "ManageMyself-Android/1.0")
                        .build();
                
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, "API连接失败", e);
                        String errorMsg = analyzeConnectionError(e);
                        notifyError(callback, errorMsg);
                    }
                    
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        try {
                            if (response.isSuccessful()) {
                                String responseBody = response.body() != null ? 
                                    response.body().string() : "";
                                
                                // 尝试解析JSON响应
                                try {
                                    JSONObject json = new JSONObject(responseBody);
                                    boolean success = json.optBoolean("success", false);
                                    String message = json.optString("message", "API响应成功");
                                    
                                    if (success) {
                                        notifySuccess(callback, "API连接成功！服务器响应: " + message);
                                    } else {
                                        notifyError(callback, "API返回错误: " + message);
                                    }
                                } catch (Exception e) {
                                    // JSON解析失败，但HTTP状态码成功
                                    notifySuccess(callback, "API连接成功！HTTP状态码: " + response.code());
                                }
                            } else {
                                notifyError(callback, "API服务器错误: HTTP " + response.code() + 
                                    " " + response.message());
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "处理响应失败", e);
                            notifyError(callback, "处理服务器响应失败: " + e.getMessage());
                        }
                    }
                });
                
            } catch (Exception e) {
                Log.e(TAG, "测试API连接时发生异常", e);
                notifyError(callback, "测试失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 分析连接错误
     */
    private static String analyzeConnectionError(IOException e) {
        String errorMsg = e.getMessage();
        if (errorMsg == null) {
            return "未知网络错误";
        }
        
        if (errorMsg.contains("Connection refused") || errorMsg.contains("连接被拒绝")) {
            return "连接被拒绝：服务器可能未启动或防火墙阻止了连接";
        } else if (errorMsg.contains("timeout") || errorMsg.contains("超时")) {
            return "连接超时：网络延迟过高或服务器响应慢";
        } else if (errorMsg.contains("UnknownHostException") || errorMsg.contains("unknown host")) {
            return "无法解析服务器地址：请检查API地址配置";
        } else if (errorMsg.contains("Network is unreachable") || errorMsg.contains("网络不可达")) {
            return "网络不可达：请检查网络连接";
        } else if (errorMsg.contains("SSL") || errorMsg.contains("certificate")) {
            return "SSL证书错误：请检查HTTPS配置";
        } else {
            return "网络连接失败: " + errorMsg;
        }
    }
    
    /**
     * 测试数据库连接
     */
    public static void testDatabaseConnection(Context context, TestCallback callback) {
        if (callback != null) {
            mainHandler.post(() -> callback.onProgress("开始测试数据库连接..."));
        }
        
        executor.execute(() -> {
            try {
                // 检查是否使用远程数据库
                DatabaseSettingsManager dbSettings = DatabaseSettingsManager.getInstance();
                boolean useRemoteDb = dbSettings.isUseRemoteDatabase(context);
                
                if (!useRemoteDb) {
                    notifySuccess(callback, "当前使用本地数据库模式，无需测试远程连接");
                    return;
                }
                
                notifyProgress(callback, "正在测试远程数据库连接...");
                
                // 测试MySQL连接
                boolean connected = MySQLConnectionHelper.getInstance().testConnection();
                
                if (connected) {
                    notifySuccess(callback, "数据库连接成功！");
                } else {
                    notifyError(callback, "数据库连接失败，请检查数据库配置");
                }
                
            } catch (Exception e) {
                Log.e(TAG, "测试数据库连接失败", e);
                notifyError(callback, "数据库连接测试失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 获取网络诊断信息
     */
    public static void getNetworkDiagnostics(Context context, TestCallback callback) {
        if (callback != null) {
            mainHandler.post(() -> callback.onProgress("正在收集网络诊断信息..."));
        }
        
        executor.execute(() -> {
            try {
                StringBuilder diagnostics = new StringBuilder();
                
                // 网络状态
                boolean networkAvailable = NetworkUtils.isNetworkAvailable(context);
                diagnostics.append("网络状态: ").append(networkAvailable ? "已连接" : "未连接").append("\n");
                
                if (networkAvailable) {
                    String networkType = NetworkUtils.getNetworkTypeDescription(context);
                    diagnostics.append("网络类型: ").append(networkType).append("\n");
                }
                
                // API配置信息
                AppConfig config = AppConfig.getInstance();
                String apiUrl = config.getApiBaseUrl();
                diagnostics.append("API地址: ").append(apiUrl != null ? apiUrl : "未配置").append("\n");
                
                // 数据库配置信息
                DatabaseSettingsManager dbSettings = DatabaseSettingsManager.getInstance();
                boolean useRemoteDb = dbSettings.isUseRemoteDatabase(context);
                diagnostics.append("数据库模式: ").append(useRemoteDb ? "远程数据库" : "本地数据库").append("\n");
                
                if (useRemoteDb) {
                    String dbHost = dbSettings.getDbHost(context);
                    String dbPort = dbSettings.getDbPort(context);
                    diagnostics.append("数据库地址: ").append(dbHost).append(":").append(dbPort).append("\n");
                }
                
                notifySuccess(callback, diagnostics.toString());
                
            } catch (Exception e) {
                Log.e(TAG, "获取网络诊断信息失败", e);
                notifyError(callback, "获取诊断信息失败: " + e.getMessage());
            }
        });
    }
    
    // 辅助方法
    private static void notifySuccess(TestCallback callback, String message) {
        if (callback != null) {
            mainHandler.post(() -> callback.onSuccess(message));
        }
    }
    
    private static void notifyError(TestCallback callback, String error) {
        if (callback != null) {
            mainHandler.post(() -> callback.onError(error));
        }
    }
    
    private static void notifyProgress(TestCallback callback, String progress) {
        if (callback != null) {
            mainHandler.post(() -> callback.onProgress(progress));
        }
    }
} 